//
//  UIScrollView+SEGSWindmill.m
//  RefreshDemo
//
//  Created by Clavis on 2019/1/2.
//  Copyright © 2019 Clavis. All rights reserved.
//

#import "UIScrollView+SEGWindmill.h"
#import <objc/runtime.h>

#if __has_include(<Commom/YYBaseHeader.h>)
#import <Commom/YYBaseHeader.h>
#else
#import "YYBaseHeader.h"
#endif

@interface UIScrollView ()
@property (nonatomic, strong) NSDate *startRefreshTime; // 上次刷新的时间
@end

@implementation UIScrollView (SEGWindmill)

- (void)setSeg_header:(SEGWindmillRefreshCommonHeader *)seg_header {
    if (seg_header != self.seg_header) {
        [self.seg_header removeFromSuperview];
        [self insertSubview:seg_header atIndex:0];
        
        [self willChangeValueForKey:@"seg_header"];
        objc_setAssociatedObject(self, _cmd, seg_header, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [self didChangeValueForKey:@"seg_header"];
    }
}

- (SEGWindmillRefreshCommonHeader *)seg_header {
    return objc_getAssociatedObject(self, @selector(setSeg_header:));
}

- (void)setSeg_footer:(SEGWindmillRefreshCommonFooter *)seg_footer {
    if (seg_footer != self.seg_footer) {
        [self.seg_footer removeFromSuperview];
        [self insertSubview:seg_footer atIndex:0];
        
        [self willChangeValueForKey:@"seg_footer"];
        objc_setAssociatedObject(self, _cmd, seg_footer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [self didChangeValueForKey:@"seg_footer"];
    }
}

- (SEGWindmillRefreshCommonFooter *)seg_footer {
    return objc_getAssociatedObject(self, @selector(setSeg_footer:));
}

- (void)setStartRefreshTime:(NSDate *)startRefreshTime {
    objc_setAssociatedObject(self, _cmd, startRefreshTime, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSDate *)startRefreshTime {
    return objc_getAssociatedObject(self, @selector(setStartRefreshTime:));
}

- (void)addWindmillWithHeaderRefreshBlock:(SEGWindmillComponentRefreshBeginBlock)headerRefreshBlock {
    self.seg_header = [SEGWindmillRefreshCommonHeader headerWithRefreshingBlock:headerRefreshBlock];
}

- (void)addWindmillWithFooterRefreshBlock:(SEGWindmillComponentRefreshBeginBlock)footerRefreshBlock {
    self.seg_footer = [SEGWindmillRefreshCommonFooter footerWithRefreshingBlock:footerRefreshBlock];
}

- (void)addWindmillWithHeaderRefreshBlock:(SEGWindmillComponentRefreshBeginBlock)headerRefreshBlock footerRefreshBlock:(SEGWindmillComponentRefreshBeginBlock)footerRefreshBlock {
    self.seg_header = [SEGWindmillRefreshCommonHeader headerWithRefreshingBlock:headerRefreshBlock];
    self.seg_footer = [SEGWindmillRefreshCommonFooter footerWithRefreshingBlock:footerRefreshBlock];
}

- (void)beginHeaderRefreshing {
    // 记录当前时间
    self.startRefreshTime = [NSDate date];
    
    // 为了兼容之前的逻辑，在第一次自动触发下拉刷新的时候，去调用VC实现的代理方法，传入刷新block进来
    SEL selector = @selector(scrollViewWillEndDragging:withVelocity:targetContentOffset:);
    if ([self.viewController respondsToSelector:selector]) {
        IMP imp = [self.viewController methodForSelector:selector];
        CGRect (*func)(id, SEL, UIScrollView *, CGPoint, CGPoint *) = (void *)imp;
        func(self.viewController, selector, self, CGPointZero, nil);
    }
    [self.seg_header beginRefreshing];
}

- (void)beginFooterRefreshing {
    [self.seg_footer beginRefreshing];
}

- (void)stopAnimatingWindmill {
    [self stopHeaderAnimatingWindmill];
    [self stopFooterAnimatingWindmill];
}

- (void)stopHeaderAnimatingWindmill {
    NSDate *stopRefreshTime = [NSDate date];
    NSTimeInterval timeInterval = stopRefreshTime.timeIntervalSince1970 - self.startRefreshTime.timeIntervalSince1970;
    if (self.startRefreshTime && timeInterval < SEGRefreshMinAnimationDuration) {
        NSTimeInterval delayInSeconds = SEGRefreshMinAnimationDuration - timeInterval;
         __weak typeof(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSTimeInterval totalTime = [NSDate date].timeIntervalSinceNow - self.startRefreshTime.timeIntervalSinceNow;
            weakSelf.startRefreshTime = nil;
            [weakSelf.seg_header endRefreshing];
        });
        return;
    }
    [self.seg_header endRefreshing];
}

- (void)stopFooterAnimatingWindmill {
    [self.seg_footer endRefreshing];
}

#pragma mark - other

- (NSInteger)seg_totalDataCount {
    NSInteger totalCount = 0;
    if ([self isKindOfClass:[UITableView class]]) {
        UITableView *tableView = (UITableView *)self;
        
        for (NSInteger section = 0; section<tableView.numberOfSections; section++) {
            totalCount += [tableView numberOfRowsInSection:section];
        }
    } else if ([self isKindOfClass:[UICollectionView class]]) {
        UICollectionView *collectionView = (UICollectionView *)self;
        
        for (NSInteger section = 0; section<collectionView.numberOfSections; section++) {
            totalCount += [collectionView numberOfItemsInSection:section];
        }
    }
    return totalCount;
}

- (void)setSeg_totalDataCount:(NSInteger)seg_totalDataCount {
    
}

@end
